//二：基于jQuery

// 1 jquery
import $ from 'jquery';
// 2 swiper
// core version + navigation, pagination modules:
import Swiper from 'swiper';
import { Pagination } from 'swiper/modules';

const $attr_options = ["color", "size"];
const $product_price = { "symbol": "$", "currency": "USD", "value": 99.00 };
const $size_charts = { "size": { "us2": [{ "cm": "83", "inch": "32.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "bust", "attr_name": "Bust" }, { "cm": "65", "inch": "25.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "waist", "attr_name": "Waist" }, { "cm": "91", "inch": "35.75", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hips", "attr_name": "Hips" }, { "cm": "147", "inch": "58", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hollowtofloor", "attr_name": "Hollow to Floor" }, { "cm": "160", "inch": "63", "ft": "5'3\"", "extensions": [], "size_chart_id": "1", "point_code": "height", "attr_name": "Height(Bare Foot)" }], "us4": [{ "cm": "85", "inch": "33.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "bust", "attr_name": "Bust" }, { "cm": "68", "inch": "26.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "waist", "attr_name": "Waist" }, { "cm": "92", "inch": "36.75", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hips", "attr_name": "Hips" }, { "cm": "147", "inch": "58", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hollowtofloor", "attr_name": "Hollow to Floor" }, { "cm": "160", "inch": "65", "ft": "5'5\"", "extensions": [], "size_chart_id": "1", "point_code": "height", "attr_name": "Height(Bare Foot)" }], "us6": [{ "cm": "88", "inch": "34.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "bust", "attr_name": "Bust" }, { "cm": "70", "inch": "27.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "waist", "attr_name": "Waist" }, { "cm": "96", "inch": "37.75", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hips", "attr_name": "Hips" }, { "cm": "150", "inch": "59", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hollowtofloor", "attr_name": "Hollow to Floor" }, { "cm": "165", "inch": "65", "ft": "5'5\"", "extensions": [], "size_chart_id": "1", "point_code": "height", "attr_name": "Height(Bare Foot)" }], "us8": [{ "cm": "90", "inch": "35.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "bust", "attr_name": "Bust" }, { "cm": "72", "inch": "28.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "waist", "attr_name": "Waist" }, { "cm": "98", "inch": "38.75", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hips", "attr_name": "Hips" }, { "cm": "150", "inch": "59", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hollowtofloor", "attr_name": "Hollow to Floor" }, { "cm": "165", "inch": "65", "ft": "5'5\"", "extensions": [], "size_chart_id": "1", "point_code": "height", "attr_name": "Height(Bare Foot)" }], "us10": [{ "cm": "93", "inch": "36.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "bust", "attr_name": "Bust" }, { "cm": "75", "inch": "29.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "waist", "attr_name": "Waist" }, { "cm": "101", "inch": "39.75", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hips", "attr_name": "Hips" }, { "cm": "152", "inch": "60", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hollowtofloor", "attr_name": "Hollow to Floor" }, { "cm": "170", "inch": "67", "ft": "5'7\"", "extensions": [], "size_chart_id": "1", "point_code": "height", "attr_name": "Height(Bare Foot)" }], "us12": [{ "cm": "97", "inch": "38", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "bust", "attr_name": "Bust" }, { "cm": "79", "inch": "31", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "waist", "attr_name": "Waist" }, { "cm": "105", "inch": "41.25", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hips", "attr_name": "Hips" }, { "cm": "152", "inch": "60", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hollowtofloor", "attr_name": "Hollow to Floor" }, { "cm": "170", "inch": "67", "ft": "5'7\"", "extensions": [], "size_chart_id": "1", "point_code": "height", "attr_name": "Height(Bare Foot)" }], "us14": [{ "cm": "100", "inch": "39.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "bust", "attr_name": "Bust" }, { "cm": "83", "inch": "32.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "waist", "attr_name": "Waist" }, { "cm": "109", "inch": "42.75", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hips", "attr_name": "Hips" }, { "cm": "155", "inch": "61", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hollowtofloor", "attr_name": "Hollow to Floor" }, { "cm": "175", "inch": "69", "ft": "5'9\"", "extensions": [], "size_chart_id": "1", "point_code": "height", "attr_name": "Height(Bare Foot)" }], "us16": [{ "cm": "104", "inch": "41", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "bust", "attr_name": "Bust" }, { "cm": "86", "inch": "34", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "waist", "attr_name": "Waist" }, { "cm": "112", "inch": "44.25", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hips", "attr_name": "Hips" }, { "cm": "155", "inch": "61", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hollowtofloor", "attr_name": "Hollow to Floor" }, { "cm": "175", "inch": "69", "ft": "5'9\"", "extensions": [], "size_chart_id": "1", "point_code": "height", "attr_name": "Height(Bare Foot)" }], "us14w": [{ "cm": "104", "inch": "41", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "bust", "attr_name": "Bust" }, { "cm": "86", "inch": "34", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "waist", "attr_name": "Waist" }, { "cm": "110", "inch": "43.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hips", "attr_name": "Hips" }, { "cm": "155", "inch": "61", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hollowtofloor", "attr_name": "Hollow to Floor" }, { "cm": "175", "inch": "69", "ft": "5'9\"", "extensions": [], "size_chart_id": "1", "point_code": "height", "attr_name": "Height(Bare Foot)" }], "us16w": [{ "cm": "109", "inch": "43", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "bust", "attr_name": "Bust" }, { "cm": "92", "inch": "36.25", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "waist", "attr_name": "Waist" }, { "cm": "116", "inch": "45.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hips", "attr_name": "Hips" }, { "cm": "155", "inch": "61", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hollowtofloor", "attr_name": "Hollow to Floor" }, { "cm": "175", "inch": "69", "ft": "5'9\"", "extensions": [], "size_chart_id": "1", "point_code": "height", "attr_name": "Height(Bare Foot)" }], "us18w": [{ "cm": "114", "inch": "45", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "bust", "attr_name": "Bust" }, { "cm": "98", "inch": "38.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "waist", "attr_name": "Waist" }, { "cm": "121", "inch": "47.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hips", "attr_name": "Hips" }, { "cm": "155", "inch": "61", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hollowtofloor", "attr_name": "Hollow to Floor" }, { "cm": "175", "inch": "69", "ft": "5'9\"", "extensions": [], "size_chart_id": "1", "point_code": "height", "attr_name": "Height(Bare Foot)" }], "us20w": [{ "cm": "119", "inch": "47", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "bust", "attr_name": "Bust" }, { "cm": "104", "inch": "40.75", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "waist", "attr_name": "Waist" }, { "cm": "126", "inch": "49.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hips", "attr_name": "Hips" }, { "cm": "155", "inch": "61", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hollowtofloor", "attr_name": "Hollow to Floor" }, { "cm": "175", "inch": "69", "ft": "5'9\"", "extensions": [], "size_chart_id": "1", "point_code": "height", "attr_name": "Height(Bare Foot)" }], "us22w": [{ "cm": "124", "inch": "49", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "bust", "attr_name": "Bust" }, { "cm": "109", "inch": "43", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "waist", "attr_name": "Waist" }, { "cm": "131", "inch": "51.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hips", "attr_name": "Hips" }, { "cm": "155", "inch": "61", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hollowtofloor", "attr_name": "Hollow to Floor" }, { "cm": "175", "inch": "69", "ft": "5'9\"", "extensions": [], "size_chart_id": "1", "point_code": "height", "attr_name": "Height(Bare Foot)" }], "us24w": [{ "cm": "130", "inch": "51", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "bust", "attr_name": "Bust" }, { "cm": "115", "inch": "45.25", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "waist", "attr_name": "Waist" }, { "cm": "136", "inch": "53.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hips", "attr_name": "Hips" }, { "cm": "155", "inch": "61", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hollowtofloor", "attr_name": "Hollow to Floor" }, { "cm": "175", "inch": "69", "ft": "5'9\"", "extensions": [], "size_chart_id": "1", "point_code": "height", "attr_name": "Height(Bare Foot)" }], "us26w": [{ "cm": "135", "inch": "53", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "bust", "attr_name": "Bust" }, { "cm": "121", "inch": "47.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "waist", "attr_name": "Waist" }, { "cm": "141", "inch": "55.5", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hips", "attr_name": "Hips" }, { "cm": "155", "inch": "61", "ft": "", "extensions": [], "size_chart_id": "1", "point_code": "hollowtofloor", "attr_name": "Hollow to Floor" }, { "cm": "175", "inch": "69", "ft": "5'9\"", "extensions": [], "size_chart_id": "1", "point_code": "height", "attr_name": "Height(Bare Foot)" }] } };
const $size_custom_image = { "waist": { "local_img_title": "Waist", "local_img": "https:\/\/img.luvdress.com\/custom\/men-suits-measure-trouser-waist.jpg.webp", "local_img_desc": "\u2022 Measure around your waist at the level where you would normally wear your pant's belt.<br \/>\n\u2022 With the tape measure snug around your waist, relax, and take the measurement.<br \/>\n\u2022 Don't be alarmed if this measurement seems larger than expected; off-the-rack pants are normally labeled as being smaller than what they really are.<br \/>" }, "shoulder": { "local_img_title": "Shoulder", "local_img": "https:\/\/img.luvdress.com\/custom\/men-suits-measure-full-shoulder-width.jpg.webp", "local_img_desc": "\u2022 Measure from the end of the right shoulder to the end of the left shoulder.<br \/>\n\u2022 We define the \"End of the Shoulder\" as where the horizontal plane of the shoulder intersects the vertical plane of the arm (see illustration).<br \/>\n\u2022 Double check measurement.<br \/>" }, "bicep": { "local_img_title": "Bicep", "local_img": "https:\/\/img.luvdress.com\/custom\/men-suits-measure-bicep.jpg.webp", "local_img_desc": "\u2022 Measure around the fullest part of the bicep with the arms by your side.<br \/>\n\u2022 You need only measure one side.<br \/>" }, "wrist": { "local_img_title": "Wrist", "local_img": "https:\/\/img.luvdress.com\/custom\/men-suits-measure-wrist.jpg.webp", "local_img_desc": "\u2022 Measure around the fullest part of the wrist.<br \/>\n\u2022 You need only measure one side.<br \/>" }, "hips": { "local_img_title": "Hips", "local_img": "https:\/\/img.luvdress.com\/custom\/men-suits-measure-hips-or-seat.jpg.webp", "local_img_desc": "\u2022 Measure around the fullest part of your hips and buttocks.<br \/>" }, "chest": { "local_img_title": "Chest", "local_img": "https:\/\/img.luvdress.com\/custom\/men-suits-measure-full-chest.jpg.webp", "local_img_desc": "\u2022 Measure around the chest and body at its fullest part (typically right under the armpits and shoulder blades, right across the nipples).<br \/>\n\u2022 Hold the tape against the body tight enough so that it does not slip down, but not so tight that it restricts breathing. It should be \"snug\".<br \/>\n\u2022 Make sure the tape is horizontal and the person's arms are by their side; then take a normal breath and measure.<br \/>\n\u2022 Do not puff out your chest.<br \/>\n\u2022 Double check this measurement.<br \/>" }, "crotch": { "local_img_title": "Crotch", "local_img": "https:\/\/img.luvdress.com\/custom\/men-suits-measure-crotch.jpg.webp", "local_img_desc": "\u2022 Measure from the front top of the pant's waistband to the back top of the pant's waistband.<br \/>\n\u2022 Make sure not to take this measurement too tight.<br \/>" }, "stomach": { "local_img_title": "Stomach", "local_img": "https:\/\/img.luvdress.com\/custom\/men-suits-measure-waist-or-stomach.jpg.webp", "local_img_desc": "\u2022 Measure around the fullest part of the waist\/stomach or right below your bottom ribs, whichever is greater.<br \/>" }, "sleevelength": { "local_img_title": "Sleeve Length", "local_img": "https:\/\/img.luvdress.com\/custom\/men-suits-measure-sleeve.jpg.webp", "local_img_desc": "\u2022 Measure from the end of either shoulder to the pinch of the corresponding hand.<br \/>\n\u2022 The \"Pinch\" of the hand is found where the base of the thumb and the base of the index finger intersect (approximately 1 inch above the index finger knuckle).<br \/>\n\u2022 Double check this measurement.<br \/>" }, "thigh": { "local_img_title": "Thigh", "local_img": "https:\/\/img.luvdress.com\/custom\/men-suits-measure-thigh.jpg.webp", "local_img_desc": "\u2022 Measure around your thigh at its widest point.<br \/>\n\u2022 You need measure only one side.<br \/>" }, "knee": { "local_img_title": "Knee", "local_img": "https:\/\/img.luvdress.com\/custom\/men-suits-measure-knee.jpg.webp", "local_img_desc": "\u2022 Measure around your knee at its widest point.<br \/>\n\u2022 You need only measure one side.<br \/>" }, "length": { "local_img_title": "Length", "local_img": "https:\/\/img.luvdress.com\/custom\/men-suits-measure-trousers-outseam.jpg.webp", "local_img_desc": "\u2022 Measure from the top of your pant's waistband to the floor along the outside of your leg.<br \/>\n\u2022 Make sure the tape is tight, that you are standing straight, and then measure. No shoes please!<br \/>\n\u2022 Double check this measurement.<br \/>" }, "jacketfrontlength": { "local_img_title": "Front Length", "local_img": "https:\/\/img.luvdress.com\/custom\/men-suits-measure-front-jacket-length.jpg.webp", "local_img_desc": "\u2022 Measure straight down the front from the base of the neck (right or left side) to the point level with your thumb knuckle.<br \/>" }, "height": { "local_img_title": "Height(Bare Foot)", "local_img": "", "local_img_desc": "\u2022 Measure barefoot from floor to top of head.<br \/>\n\u2022 Stand straight against a wall, heels together.<br \/>\n\u2022 Format examples: 5'9\", 5ft9in, 69in (inches) or 175cm (centimeters).<br \/>" }, "weight": { "local_img_title": "Weight", "local_img": "", "local_img_desc": "" } };

/**
 * 产品信息对象，用于存储产品相关信息
 * @type {Object}
 */
const product_info = {};

/**
 * 产品价格符号，如 $
 * @type {string}
 */
const symbol = $product_price.symbol;

/**
 * 产品原始价格
 * @type {number}
 */
const originalPrice = $product_price.value;

/**
 * 产品总价格，初始值为 0
 * @type {number}
 */
let totalPrice = 0;

/**
 * 滚动到指定元素
 * @param {string} ele - 要滚动到的元素的选择器
 * @param {number} [headerHeight=60] - 头部导航栏的高度，用于调整滚动位置
 */
function scrollToElement(ele, headerHeight = 60) {
    const $target = $(ele);
    if ($target.length === 0) return;

    const targetOffsetTop = $target.offset().top - headerHeight;

    // 使用 jQuery 的 animate 方法实现平滑滚动
    $('html, body').animate({
        scrollTop: targetOffsetTop
    }, 300); // 滚动时间（毫秒）
}

/**
 * 更新价格显示
 */
const updatePriceDisplay = () => {
    let totalPrice = originalPrice;
    const $spuInputs = $('.sku-list-input-js');
    $spuInputs.each(function () {
        const isCustomed = $(this).data('is-custom') === 1;
        if (!isCustomed) {
            const spuPrice = parseFloat($(this).data('selected-value-price')) || 0;
            totalPrice += spuPrice;
        }
    });

    const $spuCustoms = $('.sku-custom-js');
    $spuCustoms.each(function () {
        if ($(this).is(':checked')) {
            const spuCustomPrice = parseFloat($(this).data('custom-price')) || 0;
            console.log('custom price', spuCustomPrice);
            totalPrice += spuCustomPrice;
        }
    });

    $('#total-price').text(`${symbol}${totalPrice.toFixed(2)}`);
};
const parseHeight = (heightStr) => {
    // 使用正则表达式提取英尺和英寸部分
    const match = heightStr.match(/^(\d+)'?(\d*)"?$/);
    if (!match) {
        throw new Error("Invalid height format. Expected format like '5'6 or 5'6\"");
    }
    const feet = parseInt(match[1], 10) || 0;
    const inches = parseInt(match[2], 10) || 0;
    return { feet, inches };
}
/**
 * 初始化定制表单
 * @param {string} relatedAttr 
 * @param {string} sizeSystem 
 * @param {string} attrValue 
 */
const initCustomize = (relatedAttr, sizeSystem, attrValue) => {
    let sizeUnit;
    if (sizeSystem === 'imperial') {
        sizeUnit = 'inch';
    } else {
        sizeUnit = 'cm';
    }
    // console.log( $size_charts[relatedAttr][attrValue]);
    let selectedAttr = {};
    let pointCode;
    for (let i = 0; i < $size_charts[relatedAttr][attrValue].length; i++) {
        pointCode = $size_charts[relatedAttr][attrValue][i]['point_code'];
        if (pointCode === 'height') {
            if (sizeUnit === 'inch') {
                // 将 ft 转换为 feet 和 inches
                const { feet, inches } = parseHeight($size_charts[relatedAttr][attrValue][i]['ft']);
                $('#feet').val(feet);
                $('#inches').val(inches);
            } else {
                $('#cm').val($size_charts[relatedAttr][attrValue][i][sizeUnit]);
            }
        } else {
            selectedAttr[pointCode] = $size_charts[relatedAttr][attrValue][i][sizeUnit];
        }
    }

    // 渲染表单
    const $inputs = $(`#${relatedAttr}-custom-form-container input.custom-input-js`);
    $inputs.each(function () {
        const name = $(this).attr('name');
        if (selectedAttr[name]) {
            $(this).val(selectedAttr[name]);
        }
    });
}
/**
 * 检查自定义输入是否有效
 * @param {jQuery} $input - jQuery 包装的输入框元素
 * @returns {boolean} - 输入是否有效
 */
function checkCustomInfo($input) {
    const value = $input.val().trim();
    if ($input.prop('required') && value === '') {
        $input.addClass('is-invalid');
        // $input.next().text(`${$input.data('measurements-name')} is required.`); // 显示错误信息
        return false;
    } else if (!isNaN(value) && parseFloat(value) <= 0) {
        $input.addClass('is-invalid');
        // $input.next().text(`${$input.data('measurements-name')} must be a positive number.`); // 显示错误信息
        return false;
    } else {
        $input.removeClass('is-invalid');
        return true;
    }
}
/**
 *  处理属性点击事件
 * @param {object} $option 
 * @returns 
 */
function handleOptionClick($option) {
    // 获取属性列表容器（ul）和它的 data 属性
    const $attrElement = $option.closest('ul');
    const attrCode = $attrElement.data('attr-code'); // color, size 等

    if (!($.inArray(attrCode, $attr_options) >= 0)) return; // 确保是支持的操作类型

    console.log('attrCode2:', attrCode);

    const attrShowSizeChart = $attrElement.data('show-size-chart');
    console.log('attrShowSizeChart:', attrShowSizeChart);
    const attrIncreasePrice = $attrElement.data('increase-price');

    const valueType = $option.data('value-type'); // img、html、txt 等

    // 移除该属性组中其他选项的选中状态
    $attrElement.find('.option').attr('aria-pressed', 'false');

    // 设置当前选项为选中状态
    $option.attr('aria-pressed', 'true');

    // 更新隐藏输入框的值
    const $inputElement = $('#' + attrCode + '-input');
    $inputElement.val($option.data('value-code'));
    $inputElement.data('selected-value-name', $option.data('value-name'));
    $inputElement.data('selected-base-value-price', $option.data('base-price-increase'));
    $inputElement.data('selected-value-price', $option.data('price-increase'));

    // 隐藏错误信息
    $('#' + attrCode + '-error').addClass('d-none');

    // 更新价格（如果有需要）
    if (attrIncreasePrice === 1) {
        updatePriceDisplay();
    }

    // 如果是图片类型，更新产品预览图
    if (valueType === 'img') {
        const img_src = $option.find('img').attr('src');
        console.log('img_src:', img_src);
        const filename = img_src.split('/').pop(); // 替代 splice(-1).toString()
        console.log('filename:', filename);
        product_info['image'] = img_src; // preview only
    }

    // 显示尺寸表逻辑（如果启用）
    if (attrShowSizeChart === 1) { // .data()取的值是int,不加引号

        const selectedValueCode = $option.data('value-code');
        console.log('selectedValueCode:', selectedValueCode);

        const $chartContainer = $('#' + attrCode + '-local-chart');
        const $chartBody = $('#' + attrCode + '-local-chart-body');

        if ($size_charts[attrCode][selectedValueCode]) {
            let rows = '';
            $.each($size_charts[attrCode][selectedValueCode], function (index, detail) {
                const heightValue = detail.ft ? detail.ft : (detail.inch ? detail.inch + ' in' : '');
                const row = `
                    <tr>
                        <td>${detail.attr_name}</td>
                        <td>${heightValue}</td>
                        <td>${detail.cm} cm</td>
                    </tr>`;
                // const row = '<tr>' +
                //         '<td>'+ detail.attr_name+'</td>' +
                //         '<td>'+heightValue +'</td>' +
                //         '<td>'+detail.cm +'cm</td>' +
                //     '</tr>';                    
                rows += row;
                // $chartBody.append(row);
            });
            $chartBody.html(rows);
            $chartContainer.removeClass('d-none');
        }
    }
}
/**
 * 获取添加到购物车的数据
 * @returns {Object}
 */
function getCartData() {
    let errors = [];
    let cartData = {}; // 初始化一个空对象

    let $selected_attr_list = [];
    let $selected_size_charts = {};

    // 使用 jQuery 获取元素
    const $spu_input = $('.sku-list-input-js');
    $spu_input.each(function () {
        const $input = $(this);
        const is_customed = $input.data('is-custom') === 1;
        console.log('input:', $input);
        console.log('data-is-custom:', $input.data('is-custom'));
        console.log('is_customed:', is_customed);
        // 非定制的正常计算
        if (!is_customed) {
            const attr_code = $input.attr('name');
            const value_code = $input.val();

            if (value_code === '') {
                errors.push(`#${attr_code}-list`);
                $(`#${attr_code}-error`).removeClass('d-none');
            }
            $selected_attr_list.push({
                attr_code: attr_code,
                value_code: value_code,
                attr_name: $input.data('attr-name'),
                value_name: $input.data('selected-value-name'),
                value_price: $input.data('selected-value-price'),
                base_value_price: $input.data('selected-base-value-price')
            });
            if ($size_charts.hasOwnProperty(attr_code) && $size_charts[attr_code].hasOwnProperty(value_code)) {
                $selected_size_charts[attr_code] = $size_charts[attr_code][value_code];
            }
        }
    });
    cartData['spu_attr'] = $selected_attr_list;
    cartData['size_chart'] = $selected_size_charts;

    // 定制属性
    let $custom_list = [];
    const $spu_custom = $('.sku-custom-js');
    $spu_custom.each(function () {
        const $input = $(this);
        // 如果 checked
        if ($input.is(':checked')) {
            const attr_code = $input.data('related-attr-code');
            const size_system = $(`#${attr_code}-unit-system`).val();

            let size_unit;
            if (size_system === 'imperial') {
                size_unit = 'inch';
            } else {
                size_unit = 'cm';
            }
            // 1 特殊的测量点处理,身高和体重
            const $imperialHeight = $('#imperial-height');
            const $metricHeight = $('#metric-height');

            const $weightUnitLabel = $('#weight-unit-label');
            // 2 通用的测量点处理
            const $customElement = $(`#${attr_code}-custom-form-container`);
            const $cus_units = $customElement.find('.custom-input-js');

            let $custom_list_one = {
                attr_code: attr_code,
                attr_name: $input.data('related-attr-name'),
                custom_price: $input.data('custom-price'),
                base_custom_price: $input.data('base-custom-price'),
                size_unit: size_unit,
                list: []
            };

            // 如果有身高
            if ($imperialHeight.length) {
                // 计算单位
                let height, current_size_unit, value_with_unit;
                if (size_system === 'imperial') {
                    const $feet_input = $('#feet');
                    const feet = $feet_input.val();
                    const inches = $('#inches').val();
                    height = `${feet}'${inches}"`;
                    current_size_unit = 'ft';
                    value_with_unit = height;

                    // 检查数据是否正确
                    if (!checkCustomInfo($feet_input)) {
                        errors.push(`#${attr_code}-custom-form-container`);
                    }
                } else {
                    const $height_input = $('#cm');
                    height = $height_input.val();
                    current_size_unit = 'cm';
                    value_with_unit = `${height}${current_size_unit}`;

                    // 检查数据是否正确
                    if (!checkCustomInfo($height_input)) {
                        errors.push(`#${attr_code}-custom-form-container`);
                    }
                }

                // 添加数据
                $custom_list_one.list.push({
                    measurements_code: $imperialHeight.data('measurements-code'),
                    measurements_name: $imperialHeight.data('measurements-name'),
                    value: height,
                    size_unit: current_size_unit,
                    value_with_unit: value_with_unit
                });
            }
            // 如果有体重
            if ($weightUnitLabel.length) {
                // 检查数据是否正确
                const $weight_input = $('#weight');
                if (!checkCustomInfo($weight_input)) {
                    errors.push(`#${attr_code}-custom-form-container`);
                }
                // 计算单位
                let current_size_unit;
                if (size_system === 'imperial') {
                    current_size_unit = 'lb';
                } else {
                    current_size_unit = 'kg';
                }
                // 添加数据
                const weight = $weight_input.val();
                $custom_list_one.list.push({
                    measurements_code: $weight_input.attr('name'),
                    measurements_name: $weight_input.data('measurements-name'),
                    value: weight,
                    size_unit: current_size_unit,
                    value_with_unit: `${weight} ${current_size_unit}`
                });
            }
            // 通用的测量点处理
            $cus_units.each(function () {
                const $cus_unit = $(this);
                // 检查数据是否正确
                if (!checkCustomInfo($cus_unit)) {
                    errors.push(`#${attr_code}-custom-form-container`);
                }
                // 计算单位
                let current_size_unit;
                if (size_system === 'imperial') {
                    current_size_unit = 'in';
                } else {
                    current_size_unit = 'cm';
                }
                // 添加数据
                const value = $cus_unit.val();
                $custom_list_one.list.push({
                    measurements_code: $cus_unit.attr('name'),
                    measurements_name: $cus_unit.data('measurements-name'),
                    value: value,
                    size_unit: current_size_unit,
                    value_with_unit: `${value} ${current_size_unit}`
                });
            });

            $custom_list.push($custom_list_one);
        }
    });

    cartData['custom_attr'] = $custom_list;

    console.log('cartData:', cartData);
    return {
        errors: errors,
        data: cartData
    }
}
/**
 * 定制表单开关，开
 * @param {string} relatedAttrCode 相关属性如size
 * @param {string} relatedValueCode 相关属性值如 us6
 * @param {string} sizeSystem 尺码系统，如 imperial
 */
function custom_checked(relatedAttrCode, relatedValueCode, sizeSystem) {
    // 隐藏错误信息
    $(`#${relatedAttrCode}-error`).addClass('d-none');
    //初始化定制表单
    if (relatedValueCode) {
        $(`#${relatedAttrCode}-local-chart`).addClass('d-none');
        initCustomize(relatedAttrCode, sizeSystem, relatedValueCode);
    }
    // 显示定制表单
    $(`#${relatedAttrCode}-custom-form-container`).removeClass('d-none');
    // 更新定制标识
    $(`#${relatedAttrCode}-input`).data('is-custom', 1);//将 is-custom 数据项设置为 1 在 jQuery 的内部缓存中
    // $(`#${relatedAttrCode}-input`).attr('data-is-custom', 1);//被实际地设置到 DOM 元素上（即作为 data-is-custom="1"）
    // 置灰对应的选项
    $(`#${relatedAttrCode}-list li button`).each(function () {
        $(this).attr('disabled', 'disabled');
        $(this).css('opacity', '0.5');
        $(this).attr('aria-pressed', 'false');
        $(this).attr('aria-disabled', 'true');
    });

}
function custom_unchecked(relatedAttrCode, relatedValueCode, sizeSystem) {
    // 隐藏定制表单
    $(`#${relatedAttrCode}-custom-form-container`).addClass('d-none');
    // 隐藏错误信息
    $(`#${relatedAttrCode}-custom-form-container input`).removeClass('is-invalid');

    if (relatedValueCode) {
        // 显示局部尺码表
        $(`#${relatedAttrCode}-local-chart`).removeClass('d-none');
    }
    // 更新定制标识
    $(`#${relatedAttrCode}-input`).data('is-custom', 0);//将 is-custom 数据项设置为 0 在 jQuery 的内部缓存中
    // $(`#${relatedAttrCode}-input`).attr('data-is-custom', 0);//被实际地设置到 DOM 元素上（即作为 data-is-custom="0"）

    // 恢复对应的选项
    $(`#${relatedAttrCode}-list li button`).each(function () {

        $(this).attr('disabled', false);
        $(this).css('opacity', '');
        $(this).attr('aria-disabled', 'false');

        if ($(this).data('value-code') === relatedValueCode) {
            $(this).attr('aria-pressed', 'true');
        }
    });

}

$(function () {
    console.log('jquery 已加载！');
    console.log('swiper 已加载！');

    // swiper 轮播
    const swiper = new Swiper('#productSwiper', {
        // Optional parameters
        modules: [Pagination],//不加这儿，下面的pagination显示不出来
        direction: 'horizontal',//horizontal|vertical
        loop: true,

        // If we need pagination
        pagination: {
            el: '.swiper-pagination',
            type: 'fraction',
            currentClass: 'swiper-pagination-current', // 自定义当前页码的类名 custom-current
            totalClass: 'swiper-pagination-total',     // 自定义总页数的类名 custom-total
            renderFraction: function (currentClass, totalClass) {
                return '<span class="' + currentClass + '">' + '</span> / <span class="' + totalClass + '">' + '</span>';
            },
        },
    });

    // 点击sku时触发事件
    const $skuListJs = $('.sku-list-js');
    $skuListJs.on('click', '.option', function (e) {
        e.preventDefault();
        // 获取当前点击的选项
        const option = $(this);
        // 调用处理选项点击事件的函数
        handleOptionClick(option);
    });

    //定制 checkbox
    let relatedValueCode;
    const $skuCustomJs = $('.sku-custom-js');
    $skuCustomJs.on('change', function (event) {
        // e.preventDefault();
        const $this = $(this);
        const relatedAttrCode = $this.data('related-attr-code');
        const $relatedValueElement = $(`#${relatedAttrCode}-input`);
        relatedValueCode = $relatedValueElement.val();
        const $unitSelector = $(`#${relatedAttrCode}-unit-system`);
        if (event.target.checked) {
            console.log('checked');
            console.log('relatedValueCode:', relatedValueCode);
            custom_checked(relatedAttrCode, relatedValueCode, $unitSelector.val());
        } else {
            console.log('unchecked');
            console.log('relatedValueCode:', relatedValueCode);
            custom_unchecked(relatedAttrCode, relatedValueCode, $unitSelector.val());
        }
        //更新额外费用
        updatePriceDisplay();
    });

    // 点击尺寸单位时触发事件
    const $unitSelectorJs = $('.unit-selector-js select');
    console.log('unitSelectorJs:', $unitSelectorJs);
    $unitSelectorJs.on('change', function (event) {
        // e.preventDefault();
        const $this = $(this);
        const selectedValue = $this.val(); // 获取选中的值
        const relatedAttrCode = $this.data('related-attr-code');

        // 1 特殊的测量点处理,身高和体重
        const imperialHeight = $('#imperial-height');//
        const metricHeight = $('#metric-height');
        const weightUnitLabel = $('#weight-unit-label');
        // 2 通用的测量点处理
        const cus_units = $('.input-group-unit-js');

        if (selectedValue === 'imperial') {
            if (imperialHeight) {
                imperialHeight.removeClass('d-none');
                metricHeight.addClass('d-none');
                weightUnitLabel.text('lb');
            }
            cus_units.each(function () {
                $(this).text('in');
            });

        } else {
            if (imperialHeight) {
                imperialHeight.addClass('d-none');
                metricHeight.removeClass('d-none');
                weightUnitLabel.text('kg');
            }
            cus_units.each(function () {
                $(this).text('cm');
            });
        }

        if (relatedValueCode) {
            initCustomize(relatedAttrCode, selectedValue, relatedValueCode);
        }
    });

    //size input check
    $("input.custom-input-js,#feet, #inches,#cm,#weight").on({
        focus: function () {
            $(this).removeClass('is-invalid');
        },
        blur: function () {
            checkCustomInfo($(this));
        }
    });


    //add to cart
    $('#add-to-cart').on('click', function () {
        const data = getCartData();
        if (data.errors.length > 0) {
            scrollToElement(data.errors[0]);
            return;
        }
        // 可在此添加数据验证通过后的逻辑
    });

});





document.addEventListener('DOMContentLoaded', () => {


});